<template>
  <el-scrollbar style="height: 93vh">
    <el-card>
      <el-form inline :model="form">
        <el-form-item label="参考系类型">
          <el-select
            v-model="form.referenceName"
            size="mini"
            @change="changeName"
          >
            <el-option
              label="CGCS2000坐标系"
              value="CGCS2000坐标系"
            ></el-option>
            <el-option
              label="矿区坐标高程系统"
              value="矿区坐标高程系统"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="label">{{ node.label }}</div>
      <el-table
        v-show="form.referenceName == 'CGCS2000坐标系'"
        style="width: 100%; height: 281px; overflow: auto"
        border
        :data="datas"
        size="small"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="jzt" label="解状态" width="90">
        </el-table-column>
        <el-table-column prop="wxs" label="卫星数" width="90">
        </el-table-column>
        <el-table-column prop="jd" label="经度(°)" width="110">
        </el-table-column>
        <el-table-column prop="wd" label="纬度(°)" width="100">
        </el-table-column>
        <el-table-column prop="mh" label="CGCS2000-H(m)" width="120">
        </el-table-column>
        <el-table-column prop="mx" label="CGCS2000-x(m)" width="120">
        </el-table-column>
        <el-table-column prop="my" label="CGCS2000-y(m)" width="120">
        </el-table-column>
        <el-table-column prop="dh" label="CGCS2000-ΔH(mm)" width="140">
        </el-table-column>
        <el-table-column prop="dp" label="CGCS2000-Δp(mm)" width="140">
        </el-table-column>
        <el-table-column prop="dx" label="CGCS2000-Δx(mm)" width="140">
        </el-table-column>
        <el-table-column prop="dy" label="CGCS2000-Δy(mm)" width="140">
        </el-table-column>
        <el-table-column prop="fwj" label="方位角"></el-table-column>
        <el-table-column prop="cjsj" label="采集时间" width="180">
        </el-table-column>
      </el-table>
      <el-table
        v-show="form.referenceName == '矿区坐标高程系统'"
        style="width: 100%; height: 281px; overflow: auto"
        border
        :data="datas"
        size="small"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="jzt" label="解状态"> </el-table-column>
        <el-table-column prop="wxs" label="卫星数"> </el-table-column>
        <el-table-column prop="kqh" label="1985-H(m)" width="140">
        </el-table-column>
        <el-table-column prop="kqx" label="BJ1954-x(m)" width="140">
        </el-table-column>
        <el-table-column prop="kqy" label="BJ1954-y(m)" width="140">
        </el-table-column>
        <el-table-column prop="dkqh" label="1985-ΔH(mm)" width="140">
        </el-table-column>
        <el-table-column prop="dkqx" label="BJ1954-Δx(mm)" width="140">
        </el-table-column>
        <el-table-column prop="dkqy" label="BJ1954-Δy(mm)" width="140">
        </el-table-column>
        <el-table-column prop="fwj" label="方位角"></el-table-column>
        <el-table-column prop="cjsj" label="采集时间" width="180">
        </el-table-column>
      </el-table>
      <el-card style="height: 70vh; overflow-y: auto">
        <p>
          当前时间: <span class="sateCount">{{ dqsj }}</span
          >GPS: <span class="sateCount">{{ sdata }}</span
          >GNSS: <span class="sateCount">{{ sdatabd }}</span
          >GLONASS: <span class="sateCount">{{ sdataglon }}</span>
        </p>
        <div id="skyMap" class="sky"></div>
        <div id="snrMap" class="snr"></div>
      </el-card>
      <el-card>
        <div
          id="graphChart"
          v-show="form.referenceName == 'CGCS2000坐标系'"
          class="linetable"
        ></div>
        <div
          id="graphChart2"
          v-show="form.referenceName == '矿区坐标高程系统'"
          class="linetable"
        ></div>
      </el-card>
    </el-card>
  </el-scrollbar>
</template>

<script>
import moment from "moment";
import Axios from "axios";
import * as serviceApi from "../../../common/service.config";
import gps_pic from "../../../assets/icon2/bps.png";
import bps_pic from "../../../assets/icon2/gps.png";
import GLONASS_pic from "../../../assets/icon2/GLONASS.png";
import Highcharts from "highcharts";
import HighchartMore from "highcharts/highcharts-more";
import exportingInit from "highcharts/modules/exporting";
exportingInit(Highcharts);
HighchartMore(Highcharts);
Axios.defaults.withcredentials = true;
Highcharts.setOptions({
  lang: {
    viewFullscreen: "全屏显示",
    exitFullscreen: "退出全屏显示",
    printChart: "打印图表",
    downloadJPEG: "下载JPEG 图片",
    downloadPDF: "下载PDF文档",
    downloadPNG: "下载PNG 图片",
    downloadSVG: "下载SVG 矢量图",
    exportButtonTitle: "导出图片",
  },
});
let kkchartobj;
let kkchartobj2;
export default {
  inject: ["reload"],
  name: "RealTimeChart",
  props: {
    node: Object,
  },
  data() {
    return {
      datas: [],
      LBHOption1: [],
      LBHOption2: [],
      LBHOption3: [],
      Times: [],
      newChart: null,
      timer: null,
      sdata: "",
      sdatabd: "",
      sdataglon: "",
      dqsj: null,
      flag: false,
      form: {
        referenceName: "CGCS2000坐标系",
        referenceType: "default",
      },
      nameChange: "",
      gxoriginal: "",
      gyoriginal: "",
      referenceNameDown: "",
    };
  },
  created() {
    this.timer = setInterval(() => {
      setTimeout(() => {
        this.dqsj = moment().format("YYYY-MM-DD HH:mm:ss");
        this.queryRealData();
      }, 0);
    }, 1000);
  },
  mounted() {
    Axios({
      url: serviceApi.KB_API,
      method: "post",
      headers: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
      },
      data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\"}","serviceCode":"skyMap","timestamp":"","uuid":""}`,
    }).then((res) => {
      let skyList = res.data.parameter.list;
      let kkSkyObj = {
        gpsPosition: [],
        bdsPosition: [],
        glonPosition: [],
        gpsSignal: [],
        bdsSignal: [],
        glonSignal: [],
        gpsObj: {},
        bdsObj: {},
        glonObj: {},
      };
      for (let i = 0; i < skyList.length; i++) {
        if (skyList[i].skyType == "02") {
          kkSkyObj.gpsObj = {
            angel: Math.round(skyList[i].azimuth),
            number: "G" + skyList[i].sensorNumber,
            cno: Math.round(skyList[i].cno),
            elevation: Math.round(skyList[i].elevation),
          };
          kkSkyObj.gpsPosition.push(kkSkyObj.gpsObj);
          kkSkyObj.gpsSignal.push(kkSkyObj.gpsObj);
        } else if (skyList[i].skyType == "00") {
          kkSkyObj.bdsObj = {
            elevation: Math.round(skyList[i].elevation),
            angel: Math.round(skyList[i].azimuth),
            number: "B" + (skyList[i].sensorNumber - 100),
            cno: Math.round(skyList[i].cno),
          };
          kkSkyObj.bdsPosition.push(kkSkyObj.bdsObj);
          kkSkyObj.bdsSignal.push(kkSkyObj.bdsObj);
        } else if (skyList[i].skyType == "01") {
          kkSkyObj.glonObj = {
            elevation: Math.round(skyList[i].elevation),
            angel: Math.round(skyList[i].azimuth),
            number: "R" + (skyList[i].sensorNumber - 64),
            cno: Math.round(skyList[i].cno),
          };
          kkSkyObj.glonPosition.push(kkSkyObj.glonObj);
          kkSkyObj.glonSignal.push(kkSkyObj.glonObj);
        }
      }
      //星空图
      let StarChartOpt = Highcharts.chart("skyMap", {
        chart: {
          backgroundColor: "#fff",
          polar: true,
        },
        style: {
          color: "#333",
        },
        credits: {
          enabled: false, // 禁用版权信息
        },
        title: {
          text: "星空图",
        },
        pane: {
          startAngle: 0,
          endAngle: 360,
        },

        legend: {
          itemDistance: 10,
          symbolPadding: 10,
        },
        xAxis: {
          tickInterval: 30,
          min: 0,
          max: 360,
          labels: {
            style: {
              color: "#333",
            },
          },
        },
        yAxis: {
          min: 0,
          max: 90,
          tickInterval: 30,
          reversed: true,
          showFirstLabel: false,
          showLastLabel: true,
          labels: {
            style: {
              color: "#333",
            },
          },
        },
        exporting: {
          enabled: true,
          filename: "星空图" + "-" + String(moment().format("YYYYMMDDhh")),
        },
        tooltip: {
          valueSuffix: "°",
          formatter: function () {
            return (
              "<b>" +
              this.series.name +
              "</b><br/>卫星编号" +
              this.point.number +
              "<br/>卫星高度角" +
              Highcharts.numberFormat(this.point.elevation, 2) +
              "°<br/>卫星方位角" +
              Highcharts.numberFormat(this.x, 2) +
              "°<br/>"
            );
          },
        },
        plotOptions: {
          series: {
            pointStart: 0,
            pointInterval: 1,
          },
          column: {
            pointPadding: 0,
            groupPadding: 0,
          },
        },
        series: [
          {
            type: "scatter",
            name: '<b style="color: #333;">GPS</b>',
            marker: {
              symbol: "url(" + gps_pic + ")",
              height: 12,
              width: 12,
            },
          },
          {
            type: "scatter",
            name: '<b style="color: #333;">BDS</b>',
            marker: {
              symbol: "url(" + bps_pic + ")",
              height: 12,
              width: 12,
            },
          },
          {
            type: "scatter",
            name: '<b style="color: #333;">GLONASS</b>',
            marker: {
              symbol: "url(" + GLONASS_pic + ")",
              height: 12,
              width: 12,
            },
          },
        ],
      });
      this.chart = StarChartOpt;
      kkchartobj = StarChartOpt;
      const updatePolrChart = function (data1, data2, data3) {
        let polarChart = kkchartobj;
        let gps = [];
        for (let i = 0; i < data1.length; i++) {
          gps.push({
            x: data1[i].angel,
            y: data1[i].elevation,
            number: data1[i].number,
            elevation: data1[i].elevation,
          });
        }
        polarChart.series[0].setData(gps);

        let bds = [];
        for (let j = 0; j < data2.length; j++) {
          bds.push({
            x: data2[j].angel,
            y: data2[j].elevation,
            number: data2[j].number,
            elevation: data2[j].elevation,
          });
        }
        polarChart.series[1].setData(bds);

        let gls = [];
        for (let k = 0; k < data3.length; k++) {
          gls.push({
            x: data3[k].angel,
            y: data3[k].elevation,
            number: data3[k].number,
            elevation: data3[k].elevation,
          });
        }
        polarChart.series[2].setData(gls);
      };
      updatePolrChart(
        kkSkyObj.gpsPosition,
        kkSkyObj.bdsPosition,
        kkSkyObj.glonPosition
      );
      //信噪图
      let newChart = Highcharts.chart("snrMap", {
        chart: {
          backgroundColor: "#fff",
          type: "column",
        },
        title: {
          text: "信噪比",
        },
        xAxis: {
          type: "category",
          title: {
            text: null,
          },
          labels: {
            style: {
              color: "#333",
            },
            formatter: function () {
              return this.value;
            },
          },
        },
        legend: {
          itemDistance: 10,
          symbolPadding: 10,
        },
        yAxis: {
          min: 0,
          title: {
            text: "SNR (dB)",
            align: "high",
            style: {
              color: "#333",
            },
          },
          labels: {
            style: {
              color: "#333",
            },
            overflow: "justify",
          },
        },
        // color: ['#00bf86', '#9c02f8', '#ffb406'],
        exporting: {
          enabled: true,
          filename: "信噪比图" + "-" + String(moment().format("YYYYMMDDhh")),
        },
        tooltip: {
          valueSuffix: "dB",
          formatter: function () {
            return (
              "<b>" +
              this.series.name +
              "</b><br/>卫星编号" +
              this.point.name +
              "<br/>" +
              Highcharts.numberFormat(this.y, 2) +
              "dB"
            );
          },
        },
        plotOptions: {
          column: {
            pointPadding: 0.2,
            borderWidth: 0,
            pointWidth: 10,
          },
        },
        credits: {
          enabled: true,
          text: "",
        },
        series: [
          {
            name: '<b style="color: #333;">GPS</b>',
            color: "#0A80A4",
          },
          {
            name: '<b style="color: #333;">BDS</b>',
            color: "#FF8EAC",
          },
          {
            name: '<b style="color: #333;">GLONASS</b>',
            color: "#75CDA2",
          },
        ],
      });
      this.chart2 = newChart;
      kkchartobj2 = newChart;
      const updateHistogramChart = function (data1, data2, data3) {
        let chartsa = kkchartobj2,
          gps = [],
          bds = [],
          gls = [];

        for (let i = 0; i < data1.length; i++) {
          gps.push({
            name: data1[i].number,
            y: data1[i].cno,
          });
        }
        chartsa.series[0].setData(gps);

        for (let j = 0; j < data2.length; j++) {
          bds.push({
            name: data2[j].number,
            y: data2[j].cno,
          });
        }
        chartsa.series[1].setData(bds);

        for (let k = 0; k < data3.length; k++) {
          gls.push({
            name: data3[k].number,
            y: data3[k].cno,
          });
        }
        chartsa.series[2].setData(gls);
      };
      updateHistogramChart(
        kkSkyObj.gpsPosition,
        kkSkyObj.bdsPosition,
        kkSkyObj.glonPosition
      );
      this.sdata = kkSkyObj.gpsPosition.length;
      (this.sdatabd = kkSkyObj.bdsPosition.length),
        (this.sdataglon = kkSkyObj.glonPosition.length);
    });
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    changeName() {
      this.nameChange = this.form.referenceName;
      this.datas =[]
      this.queryRealData();
    },
    calculateAzimuth(x, y) {
      let azimuth;
      if (y < 0 && x >= 0) {
        azimuth = 270 + (Math.atan(Math.abs(x / y)) / Math.PI) * 180;
      } else if (y >= 0 && x > 0) {
        azimuth = (Math.atan(Math.abs(y / x)) / Math.PI) * 180;
      } else if (y <= 0 && x < 0) {
        azimuth = 180 + (Math.atan(Math.abs(y / x)) / Math.PI) * 180;
      } else if (y > 0 && x <= 0) {
        azimuth = 90 + (Math.atan(Math.abs(x / y)) / Math.PI) * 180;
      }
      return azimuth;
    },
    queryRealData() {
      if (this.nameChange == "") {
        this.nameChange = "CGCS2000坐标系";
      }
      if (this.nameChange == "CGCS2000坐标系") {
        this.form.referenceType = "default";
        this.gxoriginal = this.node.gxoriginal;
        this.gyoriginal = this.node.gyoriginal;
      } else if (this.nameChange == "矿区坐标高程系统") {
        this.form.referenceType = "bj54";
        this.gxoriginal = this.node.gx54original;
        this.gyoriginal = this.node.gy54original;
      }
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"referenceName\\":\\"${this.form.referenceName}\\"\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"dataType\\":\\"00\\",\\"gxoriginal\\":\\"${this.gxoriginal}\\",\\"gyoriginal\\":\\"${this.gyoriginal}\\",\\"referenceType\\":\\"${this.form.referenceType}\\",\\"latitude1\\":\\"undefined\\",\\"longitude1\\":\\"undefined\\",\\"latitude2\\":\\"undefined\\",\\"longitude2\\":\\"undefined\\",\\"latitude3\\":\\"undefined\\",\\"longitude3\\":\\"undefined\\"}","serviceCode":"${serviceApi.CONSTANT.QUERY_REAL_DATA_BY_SENSOR_NO}","timestamp":"","uuid":""}`,
      }).then((res) => {
        let datass = res.data.parameter;
        this.graph(datass);
      });
    },
    graph(datass) {
      if (this.datas.length != 0) {
        if (
          moment(datass.sensorTime).format("YYYY-MM-DD HH:mm:ss") ==
          this.datas[0].cjsj
        )
          return;
      }
      if (this.datas.length == 6) this.datas.pop();
      if (this.form.referenceName == "CGCS2000坐标系") {
        this.datas.unshift({
          jzt: datass.status,
          wxs: datass.noOfSat,
          jd: Number(datass.dldata).toFixed(8),
          wd: Number(datass.dbdata).toFixed(8),
          mh: datass.dhdata,
          mx: datass.gxdata,
          my: datass.gydata,
          dh: ((datass.dhdata - this.node.horiginal) * 1000).toFixed(1),
          dp: Math.sqrt(
            Math.pow(
              parseFloat((datass.gxdata - this.node.gxoriginal) * 1000).toFixed(
                1
              ),
              2
            ) +
              Math.pow(
                parseFloat(
                  (datass.gydata - this.node.gyoriginal) * 1000
                ).toFixed(1),
                2
              )
          ).toFixed(1),
          dx: ((datass.gxdata - this.node.gxoriginal) * 1000).toFixed(1),
          dy: ((datass.gydata - this.node.gyoriginal) * 1000).toFixed(1),
          fwj: this.calculateAzimuth(
            (datass.gxdata - this.node.gxoriginal) * 1000,
            (datass.gydata - this.node.gyoriginal) * 1000
          ).toFixed(1),
          cjsj: moment(datass.sensorTime).format("YYYY-MM-DD HH:mm:ss"),
        });
        if (this.flag) {
          this.datas[0].flag = this.flag;
          this.flag = false;
        } else {
          this.flag = true;
        }
        if (this.LBHOption1.length == 20) {
          this.LBHOption1.shift();
          this.LBHOption2.shift();
          this.LBHOption3.shift();
          this.Times.shift();
        }
        this.LBHOption1.push(
          Number(((datass.gxdata - this.node.gxoriginal) * 1000).toFixed(3))
        );
        this.LBHOption2.push(
          Number(((datass.gydata - this.node.gyoriginal) * 1000).toFixed(3))
        );
        this.LBHOption3.push(
          Number(((datass.dhdata - this.node.horiginal) * 1000).toFixed(3))
        );
        this.Times.push(moment(datass.sensorTime).format("HH:mm:ss"));
      } else if (this.form.referenceName == "矿区坐标高程系统") {
        this.datas.unshift({
          jzt: datass.status,
          wxs: datass.noOfSat,
          kqh: Number(datass.h54data).toFixed(4),
          kqx: Number(datass.x54data).toFixed(4),
          kqy: Number(datass.y54data).toFixed(4),
          dkqh: ((datass.h54data - this.node.h54original) * 1000).toFixed(1),
          dkqx: ((datass.x54data - this.node.gx54original) * 1000).toFixed(1),
          dkqy: ((datass.y54data - this.node.gy54original) * 1000).toFixed(1),
          fwj: this.calculateAzimuth(
            (datass.x54data - this.node.gx54original) * 1000,
            (datass.y54data - this.node.gy54original) * 1000
          ).toFixed(1),
          cjsj: moment(datass.sensorTime).format("YYYY-MM-DD HH:mm:ss"),
        });
        if (this.flag) {
          this.datas[0].flag = this.flag;
          this.flag = false;
        } else {
          this.flag = true;
        }
        if (this.LBHOption1.length == 20) {
          this.LBHOption1.shift();
          this.LBHOption2.shift();
          this.LBHOption3.shift();
          this.Times.shift();
        }
        this.LBHOption1.push(
          Number(((datass.x54data - this.node.gx54original) * 1000).toFixed(3))
        );
        this.LBHOption2.push(
          Number(((datass.y54data - this.node.gy54original) * 1000).toFixed(3))
        );
        this.LBHOption3.push(
          Number(((datass.h54data - this.node.h54original) * 1000).toFixed(3))
        );
        this.Times.push(moment(datass.sensorTime).format("HH:mm:ss"));
      }
      if (!this.newChart)
        this.newChart = Highcharts.chart("graphChart", {
          title: { text: "移动变形序列图" },
          xAxis: {
            title: { text: "时间" + moment().format("YYYY/MM/DD") },
            labels: {
              formatter: (e) => {
                return this.Times[e.value];
              },
            },
          },
          yAxis: { title: { text: "位移(mm)" }, lineWidth: 1 },
          legend: {
            layout: "horizontal",
            align: "center",
            verticalAlign: "top",
            name: "高度",
            type: "mm",
          },
          exporting: {
            filename:
              String(this.node.label) +
              "移动变形序列图-" +
              String(moment().format("YYYYMMDDhh")) +
              "(CGCS2000坐标系)",
            enabled: true,
          },
          tooltip: {
            dateTimeLabelFormats: {
              week: "%m:%u",
              day: "%H:%M:%S",
            },
            valueSuffix: " mm",
          },
          credits: {
            enabled: false, // 禁用版权信息
          },
          series: [{ name: "x方向" }, { name: "y方向" }, { name: "h方向" }],
          responsive: {
            rules: [
              {
                condition: {
                  maxWidth: 500,
                },
                chartOptions: {
                  legend: {
                    layout: "horizontal",
                    align: "center",
                    verticalAlign: "bottom",
                  },
                },
              },
            ],
          },
        });

      this.newChart.series[0].setData(this.LBHOption1);
      this.newChart.series[1].setData(this.LBHOption2);
      this.newChart.series[2].setData(this.LBHOption3);
      if (!this.newChart2)
        this.newChart2 = Highcharts.chart("graphChart2", {
          title: { text: "移动变形序列图" },
          xAxis: {
            title: { text: "时间" + moment().format("YYYY/MM/DD") },
            labels: {
              formatter: (e) => {
                return this.Times[e.value];
              },
            },
          },
          yAxis: { title: { text: "位移(mm)" }, lineWidth: 1 },
          legend: {
            layout: "horizontal",
            align: "center",
            verticalAlign: "top",
            name: "高度",
            type: "mm",
          },
          exporting: {
            filename:
              String(this.node.label) +
              "移动变形序列图-" +
              String(moment().format("YYYYMMDDhh")) +
              "(矿区坐标高程系统)",
            enabled: true,
          },
          tooltip: {
            dateTimeLabelFormats: {
              week: "%m:%u",
              day: "%H:%M:%S",
            },
            valueSuffix: " mm",
          },
          credits: {
            enabled: false, // 禁用版权信息
          },
          series: [{ name: "x方向" }, { name: "y方向" }, { name: "h方向" }],
          responsive: {
            rules: [
              {
                condition: {
                  maxWidth: 500,
                },
                chartOptions: {
                  legend: {
                    layout: "horizontal",
                    align: "center",
                    verticalAlign: "bottom",
                  },
                },
              },
            ],
          },
        });

      this.newChart2.series[0].setData(this.LBHOption1);
      this.newChart2.series[1].setData(this.LBHOption2);
      this.newChart2.series[2].setData(this.LBHOption3);
    },
    tableRowClassName({ row }) {
      if (row.flag) {
        return "row01";
      } else {
        return "row02";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-scrollbar /deep/ .el-scrollbar__wrap {
  overflow-x: hidden;
}
.label {
  text-align: center;
  font-size: 25px;
  line-height: 40px;
}
p {
  text-align: center;
  font-size: 16px;
  // margin-bottom: 10vh;
  .sateCount {
    color: #3a98db;
    margin-right: 5px;
  }
}
.el-card /deep/ .el-table {
  tr {
    color: #000;
    font-size: 12px;
  }
  .row01 {
    background: pink;
  }
  .row02 {
    background: #cfeed2;
  }
}
.linetable {
  width: 100%;
  height: 54vh;
}
.sky {
  width: 600px;
  height: 600px;
  float: left;
}
.snr {
  width: 600px;
  height: 600px;
  float: right;
}
.el-table::before {
  z-index: inherit;
}
</style>